package db.manager;


import java.util.List;

import protocol.meta.AppInfo;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.provider.BaseColumns;
import app.BaseApplication;

import com.google.gson.Gson;

import db.XoneDBOpenHelper;
import db.XoneDBTables.AppInfoTable;


public class ManagerAppInfo {

    public static final int SORT_BASE = 1;
    // 按时间排序
    public static final int SORT_TIME = SORT_BASE;
    // 按热度排序
    public static final int SORT_TOPIC = SORT_BASE + 1;

    public static final int GROUP_BASE = 0;
    // 全部资讯
    public static final int GROUP_DEFAULT = GROUP_BASE;
    // 只看我订阅的
    public static final int GROUP_SUBSCRIBE = GROUP_BASE + 1;
    // 只看我关注的
    public static final int GROUP_FOLLOW = GROUP_BASE + 2;
    // 只看我发布的
    public static final int GROUP_DISCUSS = GROUP_BASE + 3;
    // 获取资讯源下资讯列表
    public static final int GROUP_SOURCE_INFO_LIST = GROUP_BASE + 4;
    // 获取主题下讨论列表
    public static final int GROUP_SUBJECT_INFO_LIST = GROUP_BASE + 5;
    // 发现讨论-最热
    public static final int GROUP_POP_DISCUSS_LIST = GROUP_BASE + 6;
    // 发现讨论-猜你喜欢
    public static final int GROUP_GUESS_DISCUSS_LIST = GROUP_BASE + 7;
    // 话题下的讨论
    public static final int GROUP_TOPIC_INFO_LIST = GROUP_BASE + 8;
    // 赞我的讨论
    public static final int GROUP_PRISE_DISCUSS_LIST = GROUP_BASE + 9;
    // 用户发的讨论
    public static final int GROUP_USER_DISCUSS_LIST = GROUP_BASE + 10;
    public static String[] Projection = new String[] {
        BaseColumns._ID,              // 0
        AppInfoTable.C_ACCOUNT,       // 1
        AppInfoTable.C_INFOGROUP,     // 2
        AppInfoTable.C_SORTTYPE,      // 3
        AppInfoTable.C_TIME,          // 4
        AppInfoTable.C_JSON,          // 5
        AppInfoTable.C_INFOID         // 6
    };

    public static final int ID        = 0;
    public static final int ACCOUNT   = 1;
    public static final int INFOGROUP = 2;
    public static final int SORTTYPE  = 3;
    public static final int TIME      = 4;
    public static final int JSON      = 5;
    public static final int INFOID    = 6;

    private static Context mContext = BaseApplication.getAppInstance().getApplicationContext();


    public static Cursor getCursorByGroup(long infoGroup, long sortType) {
        Cursor cursor = null;

        StringBuilder where = new StringBuilder();
        where.append(AppInfoTable.C_INFOGROUP)
        .append("=")
        .append(infoGroup)
        .append(" AND ")
        .append(AppInfoTable.C_SORTTYPE)
        .append("=")
        .append(sortType)
        .append(" AND ")
        .append(AppInfoTable.C_ACCOUNT)
        .append("='")
        .append(ManagerAccount.getInstance().getCurrentAccountId())
        .append("'");

        cursor = mContext.getContentResolver().query(AppInfoTable.CONTENT_URI, Projection, where.toString(), null, null);

        return cursor;
    }

    public static Cursor getCursorByGroup(long infoGroup) {
        Cursor cursor = null;

        StringBuilder where = new StringBuilder();
        where.append(AppInfoTable.C_INFOGROUP)
        .append("=")
        .append(infoGroup)
        .append(" AND ")
        .append(AppInfoTable.C_ACCOUNT)
        .append("='")
        .append(ManagerAccount.getInstance().getCurrentAccountId())
        .append("'");

        cursor = mContext.getContentResolver().query(AppInfoTable.CONTENT_URI, Projection, where.toString(), null, null);

        return cursor;
    }

    /**
     * 删除所有信息
     */
    public static void delete() {
        StringBuilder where = new StringBuilder();
        where.append(AppInfoTable.C_ACCOUNT).append("='").append(ManagerAccount.getInstance().getCurrentAccountId()).append("'");

        mContext.getContentResolver().delete(AppInfoTable.CONTENT_URI, where.toString(), null);
    }

    /**
     * 根据infoGroup和sortType删除信息
     * @param infoGroup
     * @param sortType
     */
    public static void delete(long infoGroup, long sortType) {
        StringBuilder where = new StringBuilder();
        where.append(AppInfoTable.C_INFOGROUP).append("=").append(infoGroup)
        .append(" AND ")
        .append(AppInfoTable.C_SORTTYPE).append("=").append(sortType)
        .append(" AND ")
        .append(AppInfoTable.C_ACCOUNT).append("='").append(ManagerAccount.getInstance().getCurrentAccountId()).append("'");

        mContext.getContentResolver().delete(AppInfoTable.CONTENT_URI, where.toString(), null);
    }
    /**
     * 插入数据
     * @param infoGroup
     * @param sortType
     * @param array
     */
    public static void replaceAppInfo(long infoGroup, long sortType, List<AppInfo> list) {
        if (null == list || 0 == list.size()) {
            return;
        }

        StringBuilder sql = new StringBuilder();
        sql.append(" INSERT OR REPLACE INTO ");

        sql.append(AppInfoTable.TABLE_NAME);
        sql.append("(");

        sql.append(AppInfoTable.C_ACCOUNT);     // 1
        sql.append(",");
        sql.append(AppInfoTable.C_INFOGROUP);   // 2
        sql.append(",");
        sql.append(AppInfoTable.C_SORTTYPE);    // 3
        sql.append(",");
        sql.append(AppInfoTable.C_TIME);        // 4
        sql.append(",");
        sql.append(AppInfoTable.C_JSON);        // 5
        sql.append(",");
        sql.append(AppInfoTable.C_INFOID);      // 6

        sql.append(")");
        sql.append(" VALUES(");
        sql.append("?,?,?,?,?,?");
        sql.append(");");

        SQLiteDatabase database = null;
        SQLiteStatement statement = null;
        try {
            SQLiteOpenHelper openHelper = XoneDBOpenHelper.getInstance(mContext);
            database = openHelper.getWritableDatabase();
            database.beginTransaction();
            statement = database.compileStatement(sql.toString());
            int len = list.size();
            AppInfo entity = null;
            Gson gson = new Gson();
            for (int i = 0; i < len; i++) {
                entity = list.get(i);
                bindString(statement, 1, ManagerAccount.getInstance().getCurrentAccountId());
                statement.bindLong(2, infoGroup);
                statement.bindLong(3, sortType);
                statement.bindLong(4, entity.getTime());
                bindString(statement, 5, gson.toJson(entity));
                bindString(statement, 6, entity.getInfoId());
                statement.execute();
            }
            mContext.getContentResolver().notifyChange(AppInfoTable.CONTENT_URI, null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != statement) {
                statement.close();
            }

            if (null != database) {
                database.setTransactionSuccessful();
                database.endTransaction();
            }
        }
    }

    private static void bindString(SQLiteStatement stat, int index, String value) {
        if (value == null) {
            stat.bindNull(index);
        } else {
            stat.bindString(index, value);
        }
    }
}
